using UnityEngine;

[RequireComponent(typeof(Rigidbody))]
public class PlatformParenting3D : MonoBehaviour
{
    [Header("设置")]
    [Tooltip("仅当接触面朝上的角度大于此值时才吸附（0.5 ≈ 60度）")]
    [Range(0.1f, 1f)]
    public float minUpwardNormal = 0.5f;

    [Tooltip("调试模式：显示吸附状态")]
    public bool debugMode = false;

    private Rigidbody rb;
    private Rigidbody platformRb; // 平台的刚体
    private Vector3 lastPlatformPos;
    private bool isOnValidPlatform = false;

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void OnCollisionEnter(Collision collision)
    {
        if (!collision.gameObject.CompareTag("MovingPlatform")) return;

        // 检查上方接触
        bool validContact = false;
        foreach (ContactPoint contact in collision.contacts)
        {
            if (Vector3.Dot(contact.normal, Vector3.up) >= minUpwardNormal)
            {
                validContact = true;
                break;
            }
        }

        if (validContact)
        {
            platformRb = collision.rigidbody;
            lastPlatformPos = platformRb != null ? platformRb.position : collision.transform.position;
            isOnValidPlatform = true;

            if (debugMode)
                Debug.Log($"[PlatformParenting] 吸附到平台: {collision.gameObject.name}");
        }
    }

    private void OnCollisionExit(Collision collision)
    {
        if (platformRb != null && collision.rigidbody == platformRb)
        {
            isOnValidPlatform = false;
            platformRb = null;

            if (debugMode)
                Debug.Log($"[PlatformParenting] 脱离平台: {collision.gameObject.name}");
        }
    }

    private void FixedUpdate()
    {
        if (!isOnValidPlatform || platformRb == null) return;

        // 计算平台位移，精确跟随
        Vector3 newPlatformPos = platformRb.position;
        Vector3 delta = newPlatformPos - lastPlatformPos;
        rb.MovePosition(rb.position + delta);
        lastPlatformPos = newPlatformPos;
    }

    private void OnDrawGizmosSelected()
    {
        if (!debugMode) return;

        Gizmos.color = Color.cyan;
        Gizmos.DrawWireSphere(transform.position, 0.3f);
    }
}